<% layout('/layouts/default.html', {title: '车辆预结算报表', libs: ['validate','dataGrid']}){ %>
<div class="main-content">
    <div class="box box-main">
        <div class="box box-main" >
        <div class="box-header with-border">
            <div class="box-title">
                <i class="fa icon-notebook"></i> ${text('车辆预结算报表')}
            </div>
            <div class="box-tools pull-right">

            </div>
        </div>
        <#form:form id="inputForm" model="${carPreSettlement}" action="${ctx}/settlement/carpresettlement/carPreSettlement/submit" method="post" class="form-horizontal">
        <div class="box-body">
            <#form:hidden path="rowNumber"/>
            <div class="col-xs-6">
                <div class="form-group " >
                    <label class="control-label col-sm-4" title="">
                        <span class="required hide">*</span> ${text('服务订单创建日期起')}：<i class="fa icon-question hide"></i></label>
                    <div class="col-sm-8">
                        <#form:input path="createDate_gte" readonly="true" maxlength="20" class="form-control laydate width-date"
                        dataFormat="date" data-type="date" data-format="yyyy-MM-dd" data-done="createDate_lte.click()"/>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group " >
                    <label class="control-label col-sm-4" title="">
                        <span class="required hide">*</span> ${text('服务订单创建日期止')}：<i class="fa icon-question hide"></i></label>
                    <div class="col-sm-8">
                        <#form:input path="createDate_lte" readonly="true" maxlength="20" class="form-control laydate width-date"
                        dataFormat="date" data-type="date" data-format="yyyy-MM-dd"/>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group " >
                    <label class="control-label col-sm-4" title="">
                        <span class="required">*</span> ${text('客户')}：<i class="fa icon-question hide"></i></label>
                    <div class="col-sm-8">
                        <#form:select path="customerId" items="${customerList}" itemLabel="customerName"
                            itemValue="customerId" blankOption="true" class="form-control required" onchange="customerChange()"/>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="control-label col-sm-4" title="">
                        <span class="required">*</span> ${text('服务订单')}：<i class="fa icon-question hide"></i></label>
                    <div class="col-sm-8">
                        <#form:select path="serviceOrderId"  items="${serviceOrderList}" itemLabel="serviceOrderCode"
                        itemValue="serviceOrderId" data-type="paymentMethod" blankOption="true" class="form-control required" onchange="serviceOrderChange()"/>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="control-label col-sm-4" title="">
                        <span class="required hide">*</span> ${text('服务订单币种')}：<i class="fa icon-question hide"></i></label>
                    <div class="col-sm-8">
                        <#form:select path="bizhong" dictType="sys_bizhong" class="form-control" readonly="true"
                        blankOption="true" />
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="control-label col-sm-4" title="">
                        <span class="required hide">*</span> ${text('付款方式')}：<i class="fa icon-question hide"></i></label>
                    <div class="col-sm-8">
                        <#form:select path="paymentMethod" dictType="payment_method" class="form-control"
                        blankOption="true" />
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="control-label col-sm-4" title="">
                        <span class="required">*</span> ${text('车架号')}：<i class="fa icon-question hide"></i></label>
                    <div class="col-sm-8">
                        <#form:select path="frameNumber" items="${frameNumberList}"
                        itemLabel="frameNumber" itemValue="frameNumber" blankOption="true" class="form-control required" onchange="frameNumberChange()"/>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="control-label col-sm-4" title="">
                        <span class="required">*</span> ${text('车辆名称')}：<i class="fa icon-question hide"></i></label>
                    <div class="col-sm-8">
                        <#form:input path="carName" class="form-control" readOnly="readOnly" />
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="control-label col-sm-4" title="">
                        <span class="required">*</span> ${text('预结算汇率')}：<i class="fa icon-question hide"></i></label>
                    <div class="col-sm-8">
                        <#form:input path="exchangeRate" class="form-control number"/>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="control-label col-sm-4" title="">
                        <span class="required">*</span> ${text('预结算日期')}：<i class="fa icon-question hide"></i></label>
                    <div class="col-sm-8">
                        <#form:input path="date"  maxlength="20" class="form-control required" readonly="true"
                        dataFormat="date" data-type="date" data-format="yyyy-MM-dd"/>
                    </div>
                </div>
            </div>
            <div class="ml10 mr10">
                    <button type="button" class="btn btn-primary btn-sm" onclick="search()">${text('查询')}</button>
                    <button type="reset" class="btn btn-default btn-sm">${text('重置')}</button>

            </div>
                    <h4 class="form-unit">${text('客户合计信息')}</h4>
                    <div class="ml10 mr10">
                        <table id="customerGrid"></table>
                    </div>
                    <h4 class="form-unit">${text('资方合计信息')}</h4>
                    <div class="ml10 mr10">
                        <table id="investorGrid"></table>
                    </div>


            <div class="box-footer">
                <div class="row">
                    <div class="col-sm-offset-2 col-sm-10">
                        <% if(hasPermi('settlement:carpresettlement:carPreSettlement:submit')){ %>
                            <button type="button" class="btn btn-sm btn-primary" id="btnSubmit"><i class="fa fa-check"></i> ${text('提 交')}</button>&nbsp;
                        <% } %>
                        <button type="button" class="btn btn-sm btn-default" id="btnCancel" onclick="js.closeCurrentTabPage()"><i class="fa fa-reply-all"></i> ${text('关 闭')}</button>
                    </div>
                </div>
            </div>
        </div>
        </#form:form>


    </div>
    </div>
</div>
<% } %>
<script>
// 初始化DataGrid对象
$('#customerGrid').dataGrid({
    datatype: "local", // 设置本地数据
    autoGridHeight: function(){return 'auto'}, // 设置自动高度

    columnModel: [
        {header:'${text("车辆")}', name:'carName', width:150, editable:true, edittype:'text', editoptions:{'class':'form-control'}},
        {header:'${text("车架号")}', name:'frameNumber', width:150, editable:true, edittype:'text', editoptions:{'class':'form-control'}},
        {header:'${text("车价（外币）")}', name:'amount', width:150, editable:true, edittype:'text', editoptions:{'class':'form-control'}},
        {header:'${text("币种")}', name:'currency', width:150, editable:true, edittype:'text', editoptions:{'class':'form-control'},formatter: function(val, obj, row, act){
                return js.getDictLabel(${@DictUtils.getDictListJson('sys_bizhong')}, val, '${text("未知")}', true);
            }},
        {header:'${text("类型")}', name:'type', width:150, editable:true, edittype:'text', editoptions:{'class':'form-control'}},
        {header:'${text("预结算金额（RMB）")}', name:'preSettlementAmount', width:150, editable:true, edittype:'number', editoptions:{'class':'form-control number'},formatter: function(val, obj, row, act){
                return val.toFixed(4);
            }},
        {header:'${text("预结算预收余额")}', name:'preSettlementBalance', width:150, editable:true, edittype:'number',formatter: function(val, obj, row, act){
                return val.toFixed(4);
            }, editoptions:{'class':'form-control number'}},
        {header:'${text("差额")}', name:'difference', width:150, editable:true, edittype:'number',formatter: function(val, obj, row, act){
                return val.toFixed(4);
            }, editoptions:{'class':'form-control'}},
        {header:'${text("币种ID")}', name:'currencyId',hidden:true },
        {header:'${text("类型ID")}', name:'typeId', hidden:true},
    ],

    // 编辑表格的提交数据参数
    editGridInputFormListName: 'carPreSettlementCustomerList', // 提交的数据列表名
    editGridInputFormListAttrs: 'carId,frameNumber,amount,currency,type,preSettlementAmount,preSettlementBalance,difference', // 提交数据列表的属性字段

    // 加载成功后执行事件
    ajaxSuccess: function(data){

    }
});

// 初始化DataGrid对象
$('#investorGrid').dataGrid({
    datatype: "local", // 设置本地数据
    autoGridHeight: function(){return 'auto'}, // 设置自动高度

    columnModel: [
        {header:'${text("车辆")}', name:'carName', width:150, editable:true, edittype:'text', editoptions:{'class':'form-control'}},
        {header:'${text("车架号")}', name:'frameNumber', width:150, editable:true, edittype:'text', editoptions:{'class':'form-control'}},
        {header:'${text("车价（外币）")}', name:'amount', width:150, editable:true, edittype:'text', editoptions:{'class':'form-control'}},
        {header:'${text("币种")}', name:'currency', width:150, editable:true, edittype:'text', editoptions:{'class':'form-control'},formatter: function(val, obj, row, act){
                return js.getDictLabel(${@DictUtils.getDictListJson('sys_bizhong')}, val, '${text("未知")}', true);
            }},
        {header:'${text("类型")}', name:'type', width:150, editable:true, edittype:'text', editoptions:{'class':'form-control'}},
        {header:'${text("预结算金额（RMB）")}', name:'preSettlementAmount', width:150, editable:true, edittype:'number',formatter: function(val, obj, row, act){
                return val.toFixed(4);
            }, editoptions:{'class':'form-control number'}},
        {header:'${text("预付资方余额")}', name:'preSettlementBalance', width:150, editable:true, edittype:'number',formatter: function(val, obj, row, act){
                return val.toFixed(4);
            }, editoptions:{'class':'form-control number'}},
        {header:'${text("差额")}', name:'difference', width:150, editable:true, edittype:'number',formatter: function(val, obj, row, act){
                return val.toFixed(4);
            }, editoptions:{'class':'form-control'}},
        {header:'${text("币种ID")}', name:'currencyId',hidden:true },
        {header:'${text("类型ID")}', name:'typeId', hidden:true},
    ],

    // 编辑表格的提交数据参数
    editGridInputFormListName: 'carPreSettlementInvestorList', // 提交的数据列表名
    editGridInputFormListAttrs: 'carId,frameNumber,amount,currency,preSettlementAmount,preSettlementBalance,difference', // 提交数据列表的属性字段

    // 加载成功后执行事件
    ajaxSuccess: function(data){

    }
});

function search() {
    let customerId =$("#customerId").val();
    let serviceOrderId =$("#serviceOrderId").val();
    let frameNumber =$("#frameNumber").val();
    let exchangeRate =$("#exchangeRate").val();

    if(exchangeRate == null || exchangeRate == ""){
        js.showMessage("预结算汇率不能为空");
        return;
    }

    if(customerId == null || customerId == ""){
        js.showMessage("客户不能为空");
        return;
    }
    if(serviceOrderId == null || serviceOrderId == ""){
        js.showMessage("服务订单不能为空");
        return;
    }
    if(frameNumber == null || frameNumber == ""){
        js.showMessage("车架号不能为空");
        return;
    }
    let data ={"frameNumber":frameNumber,"exchangeRate":exchangeRate}

    $.ajax({
        type: "post",
        url: "${ctx}/settlement/carpresettlement/carPreSettlement/getList",
        data: data,
        dataType: "json",
        success: function(data){
            if(data == null){
                js.showMessage("请确认前置单据是否正确");
                return
            }
            $('#customerGrid').jqGrid('clearGridData');　　　　
            $("#customerGrid").jqGrid('setGridParam', {
                datatype:"local",
                data:data.carPreSettlementCustomerList
            }).trigger("reloadGrid");

            $('#investorGrid').jqGrid('clearGridData');
            $("#investorGrid").jqGrid('setGridParam', {
                datatype:"local",
                data:data.carPreSettlementInvestorList
            }).trigger("reloadGrid");
        }

    });

}

function customerChange() {
    $.ajax({
        type: "POST",
        url: "${ctx}/settlement/carpresettlement/carPreSettlement/getServiceOrderList",
        data: {"customerId": $("#customerId").val(), "createDate_gte" : $("#createDate_gte").val(), "createDate_lte" : $("#createDate_lte").val()},
        success: function (data) {
            $("#serviceOrderId").empty();
            $("#rowNumber").val('');
            $("#carName").val('');
            if (data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                    let partId = data[i].serviceOrderId;
                    let partName = data[i].serviceOrderCode;
                    let paymentMethod=data[i].paymentMethod;
                    let orderCurrency=data[i].currency;
                    let option = $("<option>").attr({
                        "value" : partId
                    }).text(partName).attr('data-type',paymentMethod).attr('data-currency',orderCurrency);
                    $("#serviceOrderId").append(option);
                }
                $("#serviceOrderId option:first").prop("selected", 'selected');
                $("#serviceOrderId").change();

            }
            if(data == ""){
                js.showErrorMessage("该客户没有服务订单！");
            }
        }
    });
}

function serviceOrderChange() {
   let ptype= $("#serviceOrderId").find(':selected').attr('data-type');
    $("#paymentMethod").val(ptype);
    $("#paymentMethod").change();
    let orderCurrency= $("#serviceOrderId").find(':selected').attr('data-currency');
    $("#bizhong").val(orderCurrency);
    $("#bizhong").change();
    $.ajax({
        type: "POST",
        url: "${ctx}/settlement/carpresettlement/carPreSettlement/getFrameNumberList",
        data: {"serviceOrderId": $("#serviceOrderId").val()},
        success: function (data) {
            $("#frameNumber").empty();
            $("#rowNumber").val('');
            $("#carName").val('');
            if (data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                    let partId = data[i];
                    let partName = data[i];
                    let option = $("<option>").attr({
                        "value" : partId
                    }).text(partName);
                    $("#frameNumber").append(option);
                }
                $("#frameNumber option:first").prop("selected", 'selected');
                $("#frameNumber").change();

            }
            if(data == ""){
                js.showErrorMessage("该服务订单没有可预结算的车架号！");
            }
        }
    });
}

function frameNumberChange(){
    $.ajax({
        type: "POST",
        url: "${ctx}/settlement/carpresettlement/carPreSettlement/getCarNameAndRowNumberList",
        data: {"serviceOrderId": $("#serviceOrderId").val(),
            "frameNumber": $("#frameNumber").val()
        },
        success: function (data) {
            $("#rowNumber").val('');
            $("#carName").val('');
            if (data.length > 0) {
                $("#rowNumber").val(data[1]);
                $("#carName").val(data[0]);
            }
            if(data == ""){
                js.showErrorMessage("该服务订单没有车架号！");
            }
        }
    });
}

$('#btnSubmit').click(function () {
    $("#btnSubmit").attr('readonly','readonly');
    let exchangeRate =$("#exchangeRate").val();

    if(exchangeRate == null || exchangeRate == ""){
        js.showMessage("预结算汇率不能为空");
        return;
    }

    let obj = {};
    obj.customerId = $("#customerId").val();
    obj.serviceOrderId = $("#serviceOrderId").val();
    obj.presttlementRate = exchangeRate;
    obj.frameNumber = $("#frameNumber").val();
    obj.carName = $("#carName").val();
    obj.rowNumber = $("#rowNumber").val();
    // 客户
    let allIds = $('#customerGrid').dataGrid('getDataIDs');
    for (let i = 0; i < allIds.length ; i++) {
        $('#customerGrid').dataGrid('saveRow', allIds[i], true);
    }
    let allData = $('#customerGrid').dataGrid('getRowData');

    let detailArr = new Array();
    for (let i = 0; i <allData.length ; i++) {
        let o = {};
        o.frameNumber = allData[i].frameNumber;
        o.balance = allData[i].difference;
        o.carPrice = allData[i].amount;
        o.currency =allData[i].currencyId;
        o.chargeType = allData[i].typeId;
        o.carName = $("#carName").val();
        o.presettlementAmount = allData[i].preSettlementAmount;
        o.presettlementAdvancesReceivedAmount = allData[i].preSettlementBalance;
        o.type=1;
        detailArr.push(o);
    }

    // 资方
    let ids = $('#investorGrid').dataGrid('getDataIDs');
    for (let i = 0; i < ids.length ; i++) {
        $('#investorGrid').dataGrid('saveRow', ids[i], true);
    }
    let all = $('#investorGrid').dataGrid('getRowData');
    for (let i = 0; i <all.length ; i++) {
        let o = {};
        o.frameNumber = all[i].frameNumber;
        o.balance = all[i].difference;
        o.carPrice = all[i].amount;
        o.currency = all[i].currencyId;
        o.chargeType = all[i].typeId;
        o.carName = $("#carName").val();
        o.presettlementAmount = all[i].preSettlementAmount;
        o.presettlementAdvancesReceivedAmount = all[i].preSettlementBalance;
        o.type=2;
        detailArr.push(o);
    }
    obj.tcarPresettlementDetailList=detailArr;
    $.ajax({
        type: "POST",
        async : false,
        dataType : "JSON",
        contentType:"application/json",
        url: "${ctx}/settlement/carpresettlement/carPreSettlement/submit",
        data: JSON.stringify(obj),
        success: function (data) {
            js.showMessage(data.message);
            //location.reload();
            var URL = '${ctx}/settlement/carpresettlement/carPreSettlement/searchlist';
            window.location.href =URL;
        }
    });
})
</script>
